<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="singleDatePicker">
          <el-form-item label="年份" size="small">
            <el-date-picker
              v-model="searchForm.year"
              type="year"
              format="yyyy"
              placeholder="选择日期"
              value-format="yyyy"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <!--<el-col class="other">-->
          <!--<el-form-item label="团队名称" size="small">-->
            <!--<el-input type="text" v-model="searchForm.teamName">-->
            <!--</el-input>-->
          <!--</el-form-item>-->
        <!--</el-col>-->
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <!--<el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>-->
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="450px">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
          <el-form-item label="选项" size="small">
            <el-select v-model="teamRow.costType" placeholder="请选择" @change="costTypeChange($event)">
              <el-option
                v-for="item in global.costTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="projectName" label="项目名称" size="small">
            <el-input type="text" v-model="teamRow.projectName"></el-input>
          </el-form-item>
          <el-form-item v-if="!teamRow.inscription" prop="outTeamName" label="支出团队" size="small">
            <el-autocomplete
              v-model="teamRow.outTeamName"
              :fetch-suggestions="querySearchOutTeam"
              @select="handleSelectOutTeam"
              placeholder="请输入内容"
              disabled
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="支出金额" size="small">
            <el-input type="number" v-model.number="teamRow.amount">
              <span slot="suffix">万元</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="date" label="支出时间" size="small">
            <el-date-picker
              v-model="teamRow.date"
              type="date"
              value-format="timestamp"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="inTeamName" label="收入团队" size="small">
            <el-autocomplete
              v-model="teamRow.inTeamName"
              :fetch-suggestions="querySearchInTeam"
              @select="handleSelectInTeam"
              placeholder="请输入内容"
              disabled
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="经办人" size="small">
            <el-autocomplete
              v-model="teamRow.agent"
              :fetch-suggestions="querySearchOperator"
              placeholder="请输入内容"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="备注说明" size="small">
            <el-input type="textarea" v-model="teamRow.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
          <el-button size="small" @click="outerVisible = false">取消</el-button>
        </div>
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs=" colConfigs"
      v-loading="listLoading">
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="120"
      >
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row)"
            type="text"
            size="small">
            结算
          </el-button>
          <!--
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
          -->
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import {
    getList,
    settleSum
  } from '@/api/teamsettlement'
  import {
    selectTeam,
    selectOperator
  } from '@/api/otherfees'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const configs = {
    props: ['colConfig'],
    template: `
  <el-table-column :label="colConfig.label">
            <el-table-column  v-for="(item, index) in colConfig.children"  :label="item.label" :width="item.width">
                <span slot-scope="scope" >
                    <span>{{scope.row[item.prop]||0}}</span>
                </span>
            </el-table-column>
  </el-table-column>
  `
  }

  const sum = function(row, column) {
    return Math.round((row.oneRentMonth + row.oneFixedMonth + row.oneWageMonth + row.twoRentMonth + row.twoFixedMonth + row.twoWageMonth + row.threeRentMonth + row.threeFixedMonth + row.threeWageMonth + row.fourRentMonth + row.fourFixedMonth + row.fourWageMonth + row.fiveRentMonth + row.fiveFixedMonth + row.fiveWageMonth + row.sixRentMonth + row.sixFixedMonth + row.sixWageMonth + row.sevenRentMonth + row.sevenFixedMonth + row.sevenWageMonth + row.eightRentMonth + row.eightFixedMonth + row.eightWageMonth + row.nineRentMonth + row.nineFixedMonth + row.nineWageMonth + row.tenRentMonth + row.tenFixedMonth + row.tenWageMonth + row.elevenRentMonth + row.elevenFixedMonth + row.elevenWageMonth + row.twelveRentMonth + row.twelveFixedMonth + row.twelveWageMonth) * 100000) / 100000
  }

  const notPaid = function(row, column) {
    if (row.status) {
      return row.notPaid
    } else {
      return sum(row, column)
    }
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'teamName', label: '团队名称', width: '150', fixed: true },
          { prop: 'year', label: '年份', width: '80', fixed: true },
          {
            label: '一月', children: [
              { prop: 'oneRentMonth', label: '房租费用(万元)', width: '120' },
              { prop: 'oneFixedMonth', label: '办公费用(万元)', width: '120' },
              { prop: 'oneWageMonth', label: '人员费用(万元)', width: '120' }
            ], component: configs
          },
          {
            label: '二月', children: [
              { prop: 'twoRentMonth', label: '房租费用(万元)', width: '120' },
              { prop: 'twoFixedMonth', label: '办公费用(万元)', width: '120' },
              { prop: 'twoWageMonth', label: '人员费用(万元)', width: '120' }
            ], component: configs
          },
          {
            label: '三月', children: [
              { prop: 'threeRentMonth', label: '房租费用(万元)', width: '120' },
              { prop: 'threeFixedMonth', label: '办公费用(万元)', width: '120' },
              { prop: 'threeWageMonth', label: '人员费用(万元)', width: '120' }
            ], component: configs
          },
          {
            label: '四月', children: [
              { prop: 'fourRentMonth', label: '房租费用(万元)', width: '120' },
              { prop: 'fourFixedMonth', label: '办公费用(万元)', width: '120' },
              { prop: 'fourWageMonth', label: '人员费用(万元)', width: '120' }
            ], component: configs
          },
          {
            label: '五月', children: [
              { prop: 'fiveRentMonth', label: '房租费用(万元)', width: '120' },
              { prop: 'fiveFixedMonth', label: '办公费用(万元)', width: '120' },
              { prop: 'fiveWageMonth', label: '人员费用(万元)', width: '120' }
            ], component: configs
          },
          {
            label: '六月', children: [
              { prop: 'sixRentMonth', label: '房租费用(万元)', width: '120' },
              { prop: 'sixFixedMonth', label: '办公费用(万元)', width: '120' },
              { prop: 'sixWageMonth', label: '人员费用(万元)', width: '120' }
            ], component: configs
          },
          {
            label: '七月', children: [
              { prop: 'sevenRentMonth', label: '房租费用(万元)', width: '120' },
              { prop: 'sevenFixedMonth', label: '办公费用(万元)', width: '120' },
              { prop: 'sevenWageMonth', label: '人员费用(万元)', width: '120' }
            ], component: configs
          },
          {
            label: '八月', children: [
              { prop: 'eightRentMonth', label: '房租费用(万元)', width: '120' },
              { prop: 'eightFixedMonth', label: '办公费用(万元)', width: '120' },
              { prop: 'eightWageMonth', label: '人员费用(万元)', width: '120' }
            ], component: configs
          },
          {
            label: '九月', children: [
              { prop: 'nineRentMonth', label: '房租费用(万元)', width: '120' },
              { prop: 'nineFixedMonth', label: '办公费用(万元)', width: '120' },
              { prop: 'nineWageMonth', label: '人员费用(万元)', width: '120' }
            ], component: configs
          },
          {
            label: '十月', children: [
              { prop: 'tenRentMonth', label: '房租费用(万元)', width: '120' },
              { prop: 'tenFixedMonth', label: '办公费用(万元)', width: '120' },
              { prop: 'tenWageMonth', label: '人员费用(万元)', width: '120' }
            ], component: configs
          },
          {
            label: '十一月', children: [
              { prop: 'elevenRentMonth', label: '房租费用(万元)', width: '120' },
              { prop: 'elevenFixedMonth', label: '办公费用(万元)', width: '120' },
              { prop: 'elevenWageMonth', label: '人员费用(万元)', width: '120' }
            ], component: configs
          },
          {
            label: '十二月', children: [
              { prop: 'twelveRentMonth', label: '房租费用(万元)', width: '120' },
              { prop: 'twelveFixedMonth', label: '办公费用(万元)', width: '120' },
              { prop: 'twelveWageMonth', label: '人员费用(万元)', width: '120' }
            ], component: configs
          },
          { prop: 'sum', label: '合计', width: '80', formatter: sum },
          { prop: 'submitted', label: '已交', width: '80' },
          { prop: 'notPaid', label: '未交', width: '80', formatter: notPaid },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        professions: [],
        typeNames: [],
        listLoading: true,
        dialogTitle: '新增团队结算',
        dialogType: 0,
        teamRow: {
          costType: 1,
          projectName: '房租费用'
        },
        teamRowClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        pca: pca,
        rules: {
          applicationTime: [
            { required: true, message: '请选择申请日期', trigger: 'change' }
          ],
          applicant: [
            { required: true, message: '请输入申请人', trigger: 'change' }
          ],
          teamName: [
            { required: true, message: '请选择团队/部门', trigger: 'change' }
          ],
          car: [
            { required: true, message: '请输入申请车辆', trigger: 'change' }
          ],
          type: [
            { required: true, message: '请选择养护类型', trigger: 'change' }
          ]
        },
        visible: false
      }
    },
    created() {
      this.$set(this.searchForm, 'year', new Date().getFullYear().toString())
      this.$set(this.searchFormList, 'year', new Date().getFullYear())
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    computed: {
      global() {
        return global
      },
      roleType() {
        return this.$store.state.user.roleType
      },
      isDirector() {
        return this.$store.state.user.isDirector
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        getList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '新增团队结算'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 1
      },
      editTeam(row) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '团队结算'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 0
        this.$set(this.teamRow, 'outTeamId', row.teamId)
        this.$set(this.teamRow, 'outTeamName', row.teamName)
        this.$set(this.teamRow, 'settleId', row.settleId)
        this.$set(this.teamRow, 'submitted', row.submitted)
        this.$set(this.teamRow, 'sumTotol', sum(row))
        const params = {
          teamName: '公司'
        }
        selectTeam(params).then(response => {
          for (const i of response.responseBody) {
            if (i.teamName === '公司') {
              this.$set(this.teamRow, 'inTeamId', i.teamId)
              this.$set(this.teamRow, 'inTeamName', i.teamName)
            }
          }
        })
      },
      submitForm(formName) {
        const params = {
          settleId: this.teamRow.settleId,
          submitted: this.teamRow.submitted,
          sumTotol: this.teamRow.sumTotol,
          costType: this.teamRow.costType,
          projectName: this.teamRow.projectName,
          amount: this.teamRow.amount || 0,
          date: this.teamRow.date,
          outTeamId: this.teamRow.outTeamId,
          outTeamName: this.teamRow.outTeamName,
          inTeamId: this.teamRow.inTeamId,
          inTeamName: this.teamRow.inTeamName,
          agent: this.teamRow.agent || '',
          remark: this.teamRow.remark || ''
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogType) {
              return
            } else {
              settleSum(params).then(response => {
                this.outerVisible = false
                this.fetchData()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        console.log(this.$refs[`popover-${scope.$index}`])
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          logId: scope.row.logId,
          isDel: 1
        }
        deleteMaintain(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      querySearchOutTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.outTeamId
        if (queryString) {
          const params = {
            teamName: queryString
          }
          selectTeam(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.teamName
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectOutTeam(item) {
        this.$set(this.teamRow, 'outTeamId', item.teamId)
        this.$set(this.teamRow, 'outTeamName', item.teamName)
      },
      querySearchInTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.inTeamId
        if (queryString) {
          const params = {
            teamName: queryString
          }
          selectTeam(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.teamName
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectInTeam(item) {
        this.$set(this.teamRow, 'inTeamId', item.teamId)
        this.$set(this.teamRow, 'inTeamName', item.teamName)
      },
      querySearchOperator(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
            teamId: this.teamRow.teamId,
            name: queryString
          }
          selectOperator(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.name
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      costTypeChange(event) {
        let obj = {}
        obj = this.global.costTypeList.find(function(item) {
          return item.value === event
        })
        this.$set(this.teamRow, 'projectName', obj.label)
      }
    },
    mounted() {
      console.log(this.pca)
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
